import os
import re


class Translate:
    head = '''digraph "classes" {\nrankdir=llll\ncharset="utf-8"'''
    tail = "}"
    template1 = '^(?P<op>[^ ]*)=>(?P<cls_op>[^ ]*): (?P<label>[^\n]*)'
    template2 = '^(?P<op1>[^ ]*)->(?P<op2>[^\n ]*)'
    node_config = {
        "operation": ("black", "box", "solid"),
        "condition": ("black", "diamond", "solid"),
        "subroutine": ("black", "Msquare", "solid"),
    }
    def __init__(self):
        self.__ops = []

    def parse_box(self, ops_dict):
        op = ops_dict.get("op")
        cls_op = ops_dict.get("cls_op")
        label = ops_dict.get("label")
        self.__ops.append(op)
        color, shape, style = self.node_config.get(cls_op)
        new_line = f'"{op}"[color = "{color}",label = "{label}", shape="{shape}", style = "{style}"];'
        return new_line

    def parse_line(self, ops_dict):
        op1 = ops_dict.get("op1")
        op2 = ops_dict.get("op2")
        arrowhead = "open"
        arrowtail = "none"

        reg = re.compile('(?P<op>[^( ]*)\((?P<op_desc>[^) ]*)')
        regMatch = reg.match(op1)
        if regMatch is not None:
            linebits = regMatch.groupdict()
            op1 = linebits.get('op')
            desc = linebits.get('op_desc')
            # op1 = f"{op1}:left"
            # if desc == 'yes':
                # op1 = f'{op1}:left'
            if desc == "left":
                desc = ""
        else:
            desc = ""
        new_line = f'"{op1}" -> "{op2}" [arrowhead="{arrowhead}", arrowtail="{arrowtail}",label="{desc}"];'
        return new_line

    def parse(self, line):
        lines = line.split("\n")
        turn = True
        new_lines = []
        for line in lines:
            if line  in ["\n",""," "]:
                turn = not turn
                continue
            if turn:
                template = self.template1
                parse = self.parse_box
            else:
                template = self.template2
                parse = self.parse_line
            reg = re.compile(template)
            regMatch = reg.match(line)
            linebits = regMatch.groupdict()
            new_line = parse(linebits)
            new_lines.append(new_line)
        new_lines = [self.head] + new_lines + [self.tail]
        new_string = "\n".join(new_lines)
        with open("parsed.dot", "w") as f:
            f.write(new_string)
        os.system("dot -Tpng parsed.dot -o output.png")


if __name__ == '__main__':
    parse1 = Translate()
    parse1.parse("./pyflowchart/code.dot")
    pass
